package com.bacel.nb.product.web.template.tag;

import freemarker.core.Environment;
import freemarker.template.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * http://www.cnblogs.com/beiyeren/p/3873683.html
 */
public class AppTag implements TemplateDirectiveModel {

    private static ApplicationContext ctx= new ClassPathXmlApplicationContext(
            "spring-context.xml");

    private final static Logger logger = LoggerFactory.getLogger(AppTag.class);

    @Override
    public void execute(Environment env, Map map, TemplateModel[] models, TemplateDirectiveBody body) throws TemplateException, IOException {
        List<Object> objs = new ArrayList<>();
        if (map.isEmpty()){
            logger.info("map is empty.");
        }
        else{
            Iterator entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String key = (String)entry.getKey();
                SimpleScalar  value = (SimpleScalar)entry.getValue();

                logger.info("Key={}, Value={}", key, value.getAsString());
                if(key.contains("tag")){
                    Object obj = ctx.getBean(value.getAsString());
                    objs.add(obj);
                }
            }
        }

        DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(new Version("2.3.23")).build();

        int i = 1;
        for(Object obj :objs){
            models[i] = wrapper.wrap(obj);
            i++;
        }
        if (body!=null) {
            body.render(env.getOut());
        }

    }

}
